// Robert van Seggelen, robertvs@gmail.com
// 2011
BandCamp = function(userOptions) {
	//default options
	var options = {
		key: 'snaefellsjokull',
		onError: function(){}
	}; 
	//merge the default options with the user defined ones
	$.extend(true, options, userOptions);
	
	function GetUrlInfo(bcUrl, callback){
		var trackResolvUrl = 'http://api.bandcamp.com/api/url/1/info?key='+options.key+'&url='+bcUrl;
		$.ajax({
			url: trackResolvUrl,
			type: "GET",
			dataType: 'jsonp',
			crossDomain: true,
			success: function(urlResult) {
				if(urlResult.error == true){
					options.onError(urlResult.error_message);
				}else{
				callback(urlResult);
				}
			},
			error: function(jqXHR, textStatus, errorThrown){
				options.onError(errorThrown);
			}
		});
	}
	function GetTrackInfo(track_id, callback){
		var trackInfoUrl = 'http://api.bandcamp.com/api/track/1/info?key='+options.key+'&track_id='+track_id;
		$.ajax({
			url: trackInfoUrl,
			type: "GET",
			dataType: 'jsonp',
			crossDomain: true,
			success: function(res) {
				if(res.error == true){
					options.onError(res.error_message);
				}else{
					callback(res);
				}
			},
			error: function(jqXHR, textStatus, errorThrown){
				options.onError(errorThrown);
			}
		});
	}
	this.GetTrack = function(bcUrl, callback){
		GetUrlInfo(bcUrl, function(urlResult){
			GetTrackInfo(urlResult.track_id, function(trackInfo){
				callback(trackInfo);
			})
		});
	}
	return this;
};